<template>
    <div class="main">
        <div class="topTitle">资产领用申请</div>
        <div class="form_content">
            <NScrollbar>
                <NSpin :show="spinShow">
                    <div class="content">
                        <div class="progressHint" v-if="hint">
                            <NIcon size="20" class="iconStyle">
                                <ErrorRound />
                            </NIcon>
                            <div style="white-space: pre-wrap" v-html="hint"></div>
                        </div>
                        <div class="progress">
                            <div style="display:flex; margin-right: 10rem;">
                                <NIcon :size="20" class="iconStyle">
                                    <ApprovalFilled />
                                </NIcon>
                                <span>审批流程</span>
                            </div>
                            <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
                            </span>
                        </div>

                        <div class="content_cen">
                            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules"
                                :label-width="110" :model="formValue" style="width: 350rem;" label-align="right">

                                <NFormItem label="事由:" path="reason">
                                    <NInput placeholder="请输入事由" style=" min-height: 120rem" type="textarea"
                                        v-model:value="formValue.reason" clearable class="commonWidth"
                                        :allow-input="noSideSpace" />
                                </NFormItem>

                                <NFormItem label="附件:">
                                    <VUpload :file-list="[]" @getList="handleUploadList" />
                                </NFormItem>

                                <NFormItem label=" ">
                                    <NButton ghost style="width: 115px;" type="primary" @click="openAssetsDevice">
                                        选择资产设备
                                    </NButton>
                                </NFormItem>
                            </NForm>
                        </div>

                        <div class="device_box">
                            <div class="device_box_table">
                                <NDataTable bordered :columns="columns" :data="formValue.assetInfoList" :pagination="false"
                                    :theme-overrides="tableThemeOverrides" :max-height="200" />
                            </div>
                        </div>
                    </div>
                </NSpin>
            </NScrollbar>
        </div>
    </div>
    <FixedAction>
        <div style="display: flex">
            <NSpace justify="start" style="flex: 0 0 43%">
                <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
                    <template #icon>
                        <img :src="VBackImg" style="width: 25rem; height: 25rem" />
                    </template>
                    返回
                </NButton>
            </NSpace>

            <NSpace justify="center">
                <NButton style="width: 115px;" type="primary" @click="confirm()" :loading="loading"
                    v-if="formValue.entityId">
                    提交申请
                </NButton>
            </NSpace>
        </div>
    </FixedAction>

    <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
        <VDialogContent @close="contentVisible = false" @submit="submit" title="保存提示">
            <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
                您确定要保存吗？
            </div>
        </VDialogContent>
    </NModal>

    <NModal :auto-focus="false" v-model:show="customVisiable">
        <VCustomVisitor @close="customVisiable = false" :customIds="customIds" @update="handleCustom" />
    </NModal>
</template>
<script setup lang="ts">
import { ref, reactive, watch, h } from 'vue'
import {
    NSpace, NForm, NFormItem, NButton, NScrollbar, NModal, useMessage, NSpin, NIcon, NDataTable, NInput,
    type FormInst, type DataTableColumns
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import VUpload from '@/views/OA/Common/Upload.vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'
import { ErrorRound } from '@vicons/material'
import VCustomVisitor from './CustomVisitor.vue'

const tags = useTagStore().tags
const route = useRoute()
const message = useMessage()
const tableThemeOverrides = { thColor: '#fff', tdColor: '#fff' }

// 资产设备cloumns
const columns: DataTableColumns = [
    {
        title: '序号',
        key: 'index',
        width: 20,
        align: 'center',
        render: (_, index) => index + 1
    },
    {
        title: '资产名称',
        key: 'assetName',
        width: 80,
        align: 'center'
    },
    {
        title: '库存剩余',
        key: 'con',
        width: 60,
        align: 'center'
    },
    {
        title: '数量',
        key: 'assetNum',
        width: 80,
        align: 'center',
        render: (row: any, index: any) => h(
            NInput, {
            placeholder: '请输入数量',
            value: row.assetNum,
            allowInput: (value: any) => {
                var regA = /^\d*$/
                const tmp: any = value.split('')
                if (tmp[0] == 0 && tmp[1] == 0) return false
                if(Number(value) === 0) return formValue.assetInfoList[index].assetNum = '1'
                if (value > row.con) return formValue.assetInfoList[index].assetNum = (row.con).toString()
                return !value || regA.test(value)
            },
            onUpdateValue: (v: any) => formValue.assetInfoList[index].assetNum = v
        })
    }
]
// 表单数据
const formValue = reactive<Record<string, any>>({
    circulationType: 'A0569',//流转类型
    assetInfoList: [],//资产设备
    reason: null, //事由
    fileIds: null, //附件
    draft: false, //草稿状态
    entityId: null //流程实体id
})
// 表单数据效验
const rules: any = {
    assetInfoList: {
        required: true,
        message: '请选择资产设备',
        type: 'array',
        trigger: ['select', 'change']
    },
    reason: {
        required: true,
        trigger: ['input', 'blur'],
        validator: (_: any, value: any) => {
            if (!value) return new Error('请输入事由')
            if (value?.length > 500) return new Error('事由字数不得超过500')
            return true
        }
    }
}
// 打开资产设备
const customVisiable = ref(false)
const customIds = ref([])
const openAssetsDevice = () => {
    customIds.value = formValue.assetInfoList.map((it: any) => it.id)
    customVisiable.value = true
}
// 资产设备选择
const handleCustom = (list: any) => {
    list.map((it: any) => it.assetNum = '1')
    formValue.assetInfoList = list

}
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')
// 获取流程id
const hint = ref()
const spinShow = ref(false)
const workFlowList = ref(' ')
const getWorkFlow = async () => {
    spinShow.value = true
    const [error, res] = await sendRequest({
        module: 'receiveOrDispatch',
        api: 'workFlow',
        override: {
            params: {
                functionCode: 'A0569'
            }
        }
    })
    if (error) return
    if (res.code !== 0) return
    formValue.entityId = res.data.entityId
    hint.value = res.data.remark
    workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
    spinShow.value = false
}
// 返回
const goBack = () => {
    const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
    tags.splice(index, 1)
    if (tags.length == 0) router.push({ path: '/OA/Workbench/UserDesktop' })
    else history.back()
}
// 附件
const handleUploadList = (v: any) => formValue.fileIds = v
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const confirm = () => {
    formRef.value?.validate(async (err) => {
        if (err) return (contentVisible.value = false)
        if (!formValue.assetInfoList?.length) return message.error('请选择资产设备')
        contentVisible.value = true
    })
}
// 提交
const contentVisible = ref(false)
const submit = async () => {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest({
        module: 'assetsManagement',
        api: 'assetCirculationApplySave',
        override: {
            data: formValue
        }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
    goSubmit()
}
// 提交完跳转我的提交
const goSubmit = () => {
    const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
    tags.splice(index, 1)
    if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
    router.push({ path: '/OA/UserCenter/Submit' })
}

watch(
    () => route,
    () => {
        if (route.path == '/OA/AssetsManagement/PersonalAssets/AssetsReceiveAdd') getWorkFlow()
    },
    { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
@mixin CommonFont {
    font-size: 16rem;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
    width: 240rem;
}

.main {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .topTitle {
        width: 100%;
        border-bottom: 1px solid #fff;
        padding: 15rem 20rem;
        margin-bottom: 20rem;
        @include CommonFont;
    }

    .form_content {
        width: 100%;
        height: 100%;
        padding: 0 20rem 0rem;

        .content {
            display: flex;
            flex-wrap: wrap;
            padding: 20rem 0 180rem;
            background-color: #ebeceb;


            .scope {
                display: flex;
                flex-wrap: wrap;
                width: 100%;

                .userBox {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 100%;
                    height: 40rem;
                    background-color: #fff;
                    border-radius: 4rem;
                    padding: 5px 10rem;
                    margin-bottom: 10rem;
                }
            }

            .device_box {
                width: 100%;
                height: auto;
                display: flex;
                justify-content: center;
                overflow: hidden;

                &_table {
                    width: 60%;
                    background-color: #fff;
                }
            }
        }
    }
}

.content_cen {
    display: flex;
    flex-direction: column;
    margin-left: 35%;
}

.iconStyle {
    margin-right: 5rem;
    color: #5fb17f;
}

.progress {
    display: flex;
    align-items: center;
    min-width: 350rem;
    max-width: 800rem;
    min-height: 50rem;
    background-color: #d5e2d8;
    border-radius: 5rem;
    margin-bottom: 10px;
    padding: 5px 15px;
    margin-left: 35%;
}

.progressHint {
    display: flex;
    min-width: 350rem;
    max-width: 800rem;
    padding: 5px 15px;
    margin-left: 35%;
}

.content::-webkit-scrollbar {
    display: none;
}

:deep(.n-spin-container) {
    width: 100%;
    height: 100%;
}

:deep(.n-scrollbar-container) {
    width: 100%;
    height: 100%;
}

:deep(.n-spin-content) {
    width: 100%;
    height: 100%;
}
</style>
  